<template>
    <el-select v-model="searchForm[data['prop']]" :placeholder="data['placeholder']" size="large" ref="select" style="width: 180px" popper-class="select-date-popper, select-tree-popper" @visible-change="visibleChange" :disabled="data['disabled']">
        <el-option :value="optionData.id" :label="optionData.name">
            <el-tree
                ref="treeRef"
                :data="orgTreeDatas"
                show-checkbox
                node-key="id"
                :default-expanded-keys="expandKeys"
                :props="defaultProps"
                @check="handleCheck"
            />
        </el-option>
    </el-select>
</template>

<script setup>
import { reactive, ref, onMounted, watch, nextTick } from 'vue';
import { deepCopy } from '@/utils/utilFns';

const treeRef = ref(null);
const expandKeys = ref([]);
const orgTreeDatas = ref([]);

const props = defineProps({
    value: {
        type: [String, Number],
        default: ''
    },
    data: {
        type: Object,
        default: () => {}
    },
    treeDatas: {
        type: Array,
        default: () => []
    },  
    defaultProps: {
        type: Object,
        default: () => {
            return {
                label: 'name',
                children: 'children'
            }
        }
    }
});

const searchForm = defineModel('searchForm');

const optionData = reactive({
    id: '',
    name: ''
});

onMounted(() => {
    orgTreeDatas.value = props.treeDatas;
    setTimeout(() => {
        init();
    });
});

watch(() => searchForm.value.orgIds, async (val) => {
    if(!treeRef.value) return;
    
    init();
},{
    immediate: true
});

// 初始化
const init = () => {
    const val = searchForm.value.orgIds;
    const keys = String(val).split(',');
    optionData.id = val;
    expandKeys.value = keys;
    
    treeRef.value.setCheckedKeys(keys);
    const nodes = treeRef.value.getCheckedNodes();
    let names = [];
    nodes.forEach(node => {
        const { children, name } = node;
        if(!children.length){
            names.push(name);
        }
    });
    
    if(names.length === 0){
        optionData.name = '请选择';
    }else{
        optionData.name = names.join(',');
    }
    
    setTreeDisabled();
};

// 设置树禁用状态
const setTreeDisabled = () => {
    const nodes = treeRef.value.getCheckedNodes(false, true);
    const datas = deepCopy(orgTreeDatas.value);
    
    const recusive = (datas, bool) => {
        datas.forEach(data => {
            const { children } = data;
            data.disabled = bool;
            
            if(children.length){
                recusive(children);
            }
        });
    };
    
    if(nodes.length === 0){
        recusive(datas, false);
    }else{
        datas.forEach(data => {
            const { id, children } = data;
            if(nodes[0].id === id){
                data.disabled = false;
                children.length && recusive(children, false);
            }else{
                data.disabled = true;
                children.length && recusive(children, true);
            }
        })
    }
    
    orgTreeDatas.value = datas;
};

// 复选框事件
const handleCheck = () => {
    const keys = treeRef.value.getCheckedKeys(true);
    const nodes = treeRef.value.getCheckedNodes();
    
    searchForm.value['orgIds'] = keys.join(',');
    
    if(Object.hasOwn(searchForm.value, 'orgNames')){
        searchForm.value['orgNames'] = nodes.join(',');
    }
};

const visibleChange = () => {
    
};

</script>

<style lang="scss" scoped>
@import "./SelectTree.scss";
</style>